import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

//创建state的存的各种数据的初始化
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

//初始化state
const state = getDefaultState()

//拿着获得的info给state重新赋值
const mutations = {
  //重置state
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  //设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  //设置名字
  SET_NAME: (state, name) => {
    state.name = name
  },
  //设置avatar
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 这里处理登录业务
  async login({ commit }, userInfo) {
    //解构出用户名与密码
    const { username, password } = userInfo
    //使用login的接口函数
    let result = await login({ username: username.trim(), password: password });
    if(result.code==20000){
      //vuex存储token
      commit('SET_TOKEN',result.data.token);
      //本地持久化存储token
      setToken(result.data.token);
      return 'ok';
    }else{
      return Promise.reject(new Error('faile'));
    }
  },

  //获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        //解构info，拿到想要的数据
        const { name, avatar } = data.teacher
        //处理info里想要的信息，就是把数据上传到vuex的state里
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 退出时，第一时间把token删掉
        resetRouter() // 重置路由，回到登录页
        commit('RESET_STATE')  //初始化state
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token,登录失败时，使用
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

